<script setup lang="ts">
import type { Reactive } from 'vue';


interface User {
    id:string,
    name:string,
    account:string,
    password:string
}

let findUsers:Reactive<Array<User>> = reactive([])
//不推荐使用:建议使用ref和reactive这种vue的响应式
let findUsersRes:Array<User> = new Array()

//不推荐:DOM不会更新
async function asyncAddUser(user_id:string,user_name:string,user_account:string,user_password:string) {
    return new Promise((resolve) => {
        findUsers.push({
            id: user_id,
            name: user_name,
            account:user_account,
            password: user_password
        })
        resolve(findUsers);
    })
    
}
onMounted(()=>{
    
})

//watch监听,这里监听的是findUsers中的变化
watch(findUsers,(oldValue:any,newValue:any)=>{
    console.log('oldValue:',oldValue,'newValue',newValue)
},{
    deep:true// 确保可以监听到数组内部的变化
})

nextTick(()=>{

})

const selectAllUsers = async() => {
    const fetchRes = await fetch('/api/findAllUsers').then(res=> {return res.json()}).then(async data=>{
        console.log(data.data)
        // let userRes
        for(let i=0;i<data.data.length;i++){
            // let userRes:Array<User> = await asyncAddUser(data.data[i]._id,data.data[i].name,data.data[i].account,data.data[i].password)
                let findUsersRes = await findUsers.push({
                    id: data.data[i]._id,
                    name:data.data[i].name,
                    account:data.data[i].account,
                    password:data.data[i].password
                })
            // console.log(userRes[i])
        }
        // findUsers.value = await data.data[0].name
    }).catch(err=>console.log(err))
}
</script>

<template>
    <div>你好</div>
    <button @click="selectAllUsers">查询用户</button>
    <span>用户有:</span><div v-for="user in findUsers">
        {{ user.id }}
    </div>
</template>

<style scoped>

</style>
